<template>
  <div class="plan-pane" style="height: 66vh">
    <!-- 工具条 -->
    <!-- 工具条：紧凑版 -->
    <div class="toolbar toolbar--compact">
      <div class="left">
        <el-input
          v-model="q.keyword"
          size="small"
          placeholder="计划内容搜索"
          clearable
          style="width: 200px"
          @keyup.enter="fetchList"
          @clear="fetchList"
        >
          <template #prefix
            ><el-icon><Search /></el-icon
          ></template>
        </el-input>

        <SingleDateRange
          v-model="q.dateRange"
          @normalized="onNorm"
          @change="fetchList"
          placeholder="计划日期范围选择"
          style="width: 400px"
        />
        <!-- <el-date-picker
          v-model="q.dateRange"
          size="small"
          type="daterange"
          range-separator="~"
          start-placeholder="计划开始日期"
          end-placeholder="计划结束日期"
          value-format="YYYY-MM-DD"
          unlink-panels
          @change="fetchList"
        /> -->
      </div>

      <div class="right">
        <el-button type="primary" :icon="Search" @click="fetchList"
          >查询</el-button
        >
        <el-button :icon="Refresh" @click="resetAndSearch">重置</el-button>
        <el-button
          size="small"
          type="primary"
          @click="openAddPlan(props.row)"
          :disabled="!row?.id"
        >
          <el-icon><Plus /></el-icon>新增指标
        </el-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-scroll">
      <el-table :data="rows" border stripe>
  <el-table-column prop="id" label="ID" width="80" align="center" />
  <el-table-column prop="assetId" label="设备ID" width="120" align="center" />
  <el-table-column prop="orderId" label="工单ID" width="120" align="center" />
  <el-table-column prop="noise" label="噪音(dB)" width="120" align="center" />
  <el-table-column prop="vibration" label="震动(mm/s)" width="120" align="center" />
  <el-table-column prop="temperature" label="温度(°C)" width="120" align="center" />
  <el-table-column prop="electricCurrent" label="电流(A)" width="120" align="center" />
  <el-table-column prop="collectTime" label="采集时间" width="180" align="center" />
  <el-table-column prop="source" label="来源" align="center" width="160">
    <template #default="{ row }">
      <el-tag
        :type="row.source === 0 ? 'info' : row.source === 1 ? 'success' : 'warning'"
        effect="light"
      >
        {{ row.source === 0 ? '人工添加' : row.source === 1 ? '首次确认' : '工单列表' }}
      </el-tag>
    </template>
  </el-table-column> 
  <el-table-column prop="createBy" label="创建人" width="120" align="center" />
  <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
  <el-table-column prop="updateBy" label="更新人" width="120" align="center" />
  <el-table-column prop="updateTime" label="更新时间" width="180" align="center" />

  <el-table-column label="操作" width="120" fixed="right" align="center">
    <template #default="{ row }">
      <el-button link type="primary" size="small" @click="openEditPlan(row)">编辑</el-button>
      <el-button link type="danger" size="small" @click="onRemove(row)">删除</el-button>
    </template>
  </el-table-column>
</el-table>

    </div>

    <!-- 分页 -->
    <!-- <div class="pager" v-if="total > 0">
      <el-pagination
        v-model:current-page="q.pageNum"
        v-model:page-size="q.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="fetchList"
        @size-change="fetchList"
      />
    </div> -->

    <el-pagination
      v-if="total > 0"
      class="wo-pager"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      v-model:current-page="q.pageNum"
      v-model:page-size="q.pageSize"
      @current-change="fetchList"
      @size-change="fetchList"
    />


     
  </div> 
  <CollectDataDialog
    ref="createDialog"
    mode="create" 
    @confirm="handleConfirm"
  />

  <EditCriticalDialog ref="editDialog" @confirm="handleUpdate" />
  <!-- <CollectDataDialog
    ref="editDialog"
    mode="edit"
    :plan="editingPlan"
    @confirm="handleConfirm"
  /> -->
</template>

<script setup>
import { ref, watch, computed, reactive } from "vue";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import { listCritical, delCritical,addbatchCritical, updateCritical } from "@/api/sbtz/critical";
import EditCriticalDialog from "@/components/sbtz/critical/EditCriticalDialog.vue";
import CollectDataDialog from "@/components/sbtz/order/CollectDataDialog.vue";
import { ElMessageBox, ElMessage } from "element-plus";

const props = defineProps({
  row: { type: Object, default: () => ({}) },
  onAddPlan: { type: Function, default: null },
  height: { type: [Number, String], default: 480 },
  refreshTick: { type: [Number, String], default: 0 },
});
const emit = defineEmits(["view", "edit", "remove"]);

const editSparesVisible = ref(false); 

const createDialog = ref();
const editDialog = ref();
const addPlanAsset = ref(null);
const editingPlan = ref(null);

  
function openAddPlan(row) {
  console.log(row)
  addPlanAsset.value = row;
  createDialog.value?.open(); // ✅ 调用子组件的 open() 方法
}

function openEditPlan(row) {
  editDialog.value?.open(row);
}


async function handleUpdate(data) {
  try {
    await updateCritical(data);
    ElMessage.success("更新成功");
    fetchList();
  } catch (e) {
    ElMessage.error("更新失败");
  }
}

async function onRemove(row) {
  try {
    await ElMessageBox.confirm(
      `确认删除计划「${row.title || row.id}」吗？`,
      "提示",
      {
        type: "warning",
        confirmButtonText: "删除",
        cancelButtonText: "取消",
      }
    );
    await delCritical(row.id); // ✅ 单个 id
    ElMessage.success("删除成功");
    fetchList(); // 重新加载列表
  } catch (e) {
    // 用户取消或接口报错
  }
}

const rows = ref([]);
const total = ref(0);
const loading = ref(false);
const q = reactive({ keyword: "", dateRange: null, pageNum: 1, pageSize: 20 });
 

async function handleConfirm({ mode, data }) {
  const assetId = addPlanAsset.value?.id || props.row?.id;
  if (!assetId) return ElMessage.error("请先选择设备节点");

  // ✅ 格式转换
  const payload = data.map((item) => ({
    assetId,
    noise: item.noise ?? 0,
    vibration: item.vibration ?? 0,
    temperature: item.temperature ?? 0,
    electricCurrent: item.current ?? 0,
    collectTime: item.collectTime || new Date().toISOString().slice(0, 19).replace('T', ' '),
    source: 0,
    isDelete: 0,
  }));

  console.log("✅ 最终提交 payload:", payload);

  try {
    if (mode === "create") {
      await addbatchCritical(payload);
      ElMessage.success("新增采集数据成功");
    } else {
      await updateCritical(payload);
      ElMessage.success("编辑采集数据成功");
    }

    // ✅ 刷新列表
    await fetchList();

    // ✅ 成功后关闭弹窗
    if (mode === "create") {
      createDialog.value?.close()
    } else {
      editDialog.value?.close();
    }

  } catch (e) {
    console.error(e);
    ElMessage.error("操作失败，请稍后重试");
  }
}




const tableHeight = computed(() => {
  const h = String(props.height);
  if (/^\d+$/.test(h)) return Number(h); // 给工具条/分页预留空间
  return null;
});

 
/** 统一 rows 解析 */
function pickRows(res) {
  if (Array.isArray(res?.rows)) return res.rows;
  if (Array.isArray(res?.data?.rows)) return res.data.rows;
  if (Array.isArray(res?.data)) return res.data;
  if (Array.isArray(res)) return res;
  return [];
}

async function fetchList() {
  if (!props.row?.id) {
    rows.value = [];
    total.value = 0;
    return;
  }
  loading.value = true;
  try {
    const params = {
      pageNum: q.pageNum,
      pageSize: q.pageSize,
      assetId: props.row?.id,
      keyword: q.keyword || null,
      "params[beginTime]": Array.isArray(q.dateRange) ? q.dateRange[0] : null,
      "params[endTime]": Array.isArray(q.dateRange) ? q.dateRange[1] : null,
    };
    const res = await listCritical(params);
    rows.value = res.rows || res.data?.rows || []; // ✅ 直接赋值
    total.value = res.total || res.data?.total || rows.value.length;
  } finally {
    loading.value = false;
  }
}


function toNum(v) {
  const n = Number(v);
  return Number.isFinite(n) ? n : null;
}

function mapPlanRow(p) {
  return {
    ...p,
    spareInfos: Array.isArray(p.spares)
      ? p.spares.map((s) => {
          const stockTotal = toNum(s.stockTotal ?? s.stock_all ?? s.totalStock);
          const stockAvailable = toNum(
            s.stockAvailable ?? s.stock_now ?? s.currentStock
          );
          return {
            id: s.spareId,
            code: s.spareCode ?? s.code,
            name: s.spareName ?? s.name,
            qty: s.qty,
            type: s.spareType, 
            stockTotal: s.stockTotal,
            stockAvailable: s.stockAvailable,
            // 需要的话也可预计算已用
            used:
              s.stockTotal != null && s.stockAvailable != null
                ? s.stockTotal - s.stockAvailable
                : null,
          };
        })
      : [],
  };
}

function attachSpareList(p = {}) {
  const spares = Array.isArray(p.spares) ? p.spares : [];
  const spareList = spares.map((s) => ({
    id: s?.spareId ?? s?.id ?? null,
    code: s?.spareCode ?? s?.code ?? "",
    name: s?.spareName ?? s?.name ?? "",
    type: Number(s?.spareType ?? 0),
    qty: Number(s?.qty ?? 0),
    orderDate: s?.spareOrderDate ?? s?.orderDate ?? null,
    unit: s?.spare?.unit ?? s?.unit ?? "",
    stockNow: Number(s?.stockAvailable ?? s?.stockNow ?? 0),
    stockAll: Number(s?.stockTotal ?? s?.stockAll ?? 0),
    usedQty: Number(s?.usedQty ?? 0),
  }));
  return { ...p, spareList };
}

function expandPlansToRows(list = []) {
  const out = [];
  for (const p of list) {
    const base = {
      id: p.id,
      assetId: p.assetId,
      assetName: p.assetName,
      title: p.title,
      planContent: p.planContent,
      tradeCode: p.tradeCode,
      planDate: p.planDate,
      planType: p.planType,
      status: p.status,
      needSpare: Number(p.needSpare) === 1,
      createTime: p.createTime,
    };
    // 没有 spares 也保留一行
    const rels = Array.isArray(p.spares) && p.spares.length ? p.spares : [null];
    for (const s of rels) {
      out.push({
        ...base,
        spareId: s?.spareId ?? null,
        spareCode: s?.spareCode ?? s?.code ?? "",
        spareName: s?.spareName ?? s?.name ?? "",
        unit: s?.spare?.unit ?? s?.unit ?? "",
        spareType: Number(s?.spareType ?? 0),
        spareStatus: Number(s?.spareStatus ?? 0),
        qty: Number(s?.qty ?? 0),
        orderDate: s?.spareOrderDate ?? s?.orderDate ?? null,
      });
    }
  }
  return out;
}

function onNorm(range) {
  const toYmd = (d) =>
    typeof d === "string"
      ? d.slice(0, 10)
      : `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(
          2,
          "0"
        )}-${String(d.getDate()).padStart(2, "0")}`;
  q.dateRange = Array.isArray(range) ? range.map(toYmd) : null;
}
function handleAdd() {
  // 优先调用父传入的 onAddPlan（openAddPlan），否则回退到 onAdd
  if (typeof props.onAddPlan === "function") return props.onAddPlan(props.row);
  if (typeof props.onAdd === "function") return props.onAdd(props.row);
}

/** 小工具 */
const dateSort = (a, b) =>
  (a ? new Date(a).getTime() : 0) - (b ? new Date(b).getTime() : 0);
function fmtDate(d) {
  if (!d) return "-";
  const t = new Date(d);
  if (isNaN(t)) return "-";
  const y = t.getFullYear(),
    m = String(t.getMonth() + 1).padStart(2, "0"),
    D = String(t.getDate()).padStart(2, "0");
  return `${y}-${m}-${D}`;
}
function fmtDateTime(d) {
  if (!d) return "-";
  const t = new Date(d);
  if (isNaN(t)) return "-";
  const y = t.getFullYear(),
    m = String(t.getMonth() + 1).padStart(2, "0"),
    D = String(t.getDate()).padStart(2, "0");
  const h = String(t.getHours()).padStart(2, "0"),
    mi = String(t.getMinutes()).padStart(2, "0");
  return `${y}-${m}-${D} ${h}:${mi}`;
}

watch(
  () => props.row?.id,
  () => {
    q.pageNum = 1;
    fetchList();
  },
  { immediate: true }
);
watch(
  () => props.refreshTick,
  () => {
    // 不改页码，只做刷新；如需回到第1页可在这里重置 pageNum
    fetchList();
  }
);

/** 表样式 */
const headerCellStyle = () => ({
  background: "linear-gradient(180deg, #fafafa, #f3f4f6)",
  color: "#344054",
  fontWeight: 700,
  borderColor: "#eef0f3",
});
const cellStyle = () => ({ color: "#1f2937", borderColor: "#f1f2f5" });
</script>

<style scoped>
.plan-pane {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 10px;
  padding: 10px 12px;
}
.toolbar .left {
  display: flex;
  gap: 10px;
  align-items: center;
}
.toolbar .right {
  display: flex;
  gap: 8px;
}
.plan-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 28px rgba(0, 0, 0, 0.05);
}
.pager {
  display: flex;
  justify-content: flex-end;
}

/* 紧凑工具条（图1风格） */
.toolbar--compact {
  --ctl-h: 28px; /* 小号控件高度 */
  --ctl-fs: 12px; /* 小号字体 */
  padding: 6px 10px; /* 更紧的左右内边距 */
}
.toolbar--compact .left {
  gap: 8px;
}
.toolbar--compact .right {
  gap: 6px;
}

/* 统一控件尺寸与描边（Element Plus 用 box-shadow 作边框） */
.toolbar--compact :deep(.el-input__wrapper),
.toolbar--compact :deep(.el-select .el-select__wrapper),
.toolbar--compact :deep(.el-range-editor) {
  height: var(--ctl-h);
  font-size: var(--ctl-fs);
  padding: 0 8px;
}

/* 小号按钮 */
.toolbar--compact :deep(.el-button) {
  height: var(--ctl-h);
  padding: 0 10px;
  font-size: var(--ctl-fs);
}

/* 占位符更轻一些（可选） */
.toolbar--compact :deep(.el-input__inner::placeholder),
.toolbar--compact :deep(.el-range-editor__input::placeholder) {
  color: var(--el-text-color-placeholder);
}

/* 外层容器：允许水平/垂直滚动 */
.table-scroll {
  /* 高度占满可用空间，超出滚动 */ 
  overflow: auto; /* 同时支持横向&纵向滚动 */
}

/* 让 el-table 根据列宽“自然撑开”，从而产生横向滚动 */
.wide-table {
  width: max-content; /* 关键：按内容宽度展开 */
  min-width: 100%; /* 小于容器时至少占满容器 */
}

/* 保持你的原有美化 */
.plan-table {
  border-radius: 12px;
  overflow: hidden; /* 保留阴影圆角 */
  box-shadow: 0 10px 28px rgba(0, 0, 0, 0.05);
}

/* 统一用 el-table 的边框色 */
/* 单元格内的“列表”容器：一行一个备件，竖向堆叠 */
.stack {
  display: flex;
  flex-direction: column;
  gap: 8px; /* 每个备件行之间的间距 */ 
}

/* 每个备件一行 */
.line {
  display: flex;
  align-items: center;
  min-height: 24px; /* 与小号表格行高协调，可按需调整 */
}

/* 备件名称一行显示，超出省略号 */
.one-line {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

/* 数值列更居中一些（可选） */
.num-col {
  align-items: stretch;
}
.num-col .line {
  justify-content: center;
}

/* 分页粘底的外观（与工单页一致） */
.wo-pager {
  position: sticky;   /* 如不需要粘底，只留下面四行也可以 */
  bottom: 0;
  z-index: 5;
  background: #fff;
  border-top: 1px solid #eef2f6;
  padding: 6px 8px;
  display: flex;
  justify-content: flex-end;
}

</style>
